//
//  LXPermissionLocation.swift
//  LXPermissionAuth
//
//  Created by yoctech on 2021/8/18.
//

import UIKit
import MapKit

@objc class LXPermissionLocation: NSObject, LXPermissionProtocol {
    @objc private static let locationAuthManager = CLLocationManager()
    @objc public static func auth(autoRequestIfNot: Bool, clouser: @escaping LXAuthClouser) {
        let aStatus = CLLocationManager.authorizationStatus()
        switch aStatus {
        case .notDetermined:
            if !autoRequestIfNot {
                clouser(false, .other)
                return
            }
            //由于IOS8中定位的授权机制改变 需要进行手动授权
            locationAuthManager.requestAlwaysAuthorization()
            locationAuthManager.requestWhenInUseAuthorization()
            let status = CLLocationManager.authorizationStatus()
            if  status == .authorizedAlways || status == .authorizedWhenInUse {
                DispatchQueue.main.async {
                    clouser(true && CLLocationManager.locationServicesEnabled(), .authorized)
                }
            }else{
                DispatchQueue.main.async {
                    clouser(false, .other)
                }
            }
        case .restricted:
            clouser(false, .restricted)
        case .denied:
            clouser(false, .denied)
        case .authorizedAlways:
            clouser(true && CLLocationManager.locationServicesEnabled(), .authorized)
        case .authorizedWhenInUse:
            clouser(true && CLLocationManager.locationServicesEnabled(), .authorized)
        @unknown default:
            clouser(false, .other)
        }
    }
}
